/* 
 * File:   netevent.cpp
 * Author: zhouxich
 * Description: read事件跟出错事件的回调函数
 */
#include "server.h"


void eventcb(struct bufferevent* bev, short events, void* arg){

	bufferevent* temp_bev = (struct bufferevent*)arg;
	
	/*接收到结束符，释放对应bufferevent,同时会关闭底层套接字*/
	if (events & BEV_EVENT_EOF){
		cout <<  "closing..." << endl;
		bufferevent_free(temp_bev);
		/*出错，释放对应bufferevent,同时会关闭底层套接字*/
	}else if (events & BEV_EVENT_ERROR){
		cout << strerror(errno) << endl;
		bufferevent_free(temp_bev);
	}
}


void on_read(struct bufferevent* bev, void* ctx){

	struct evbuffer* input;
	size_t len;

	/*获得input buffer*/
	input = bufferevent_get_input(bev);

	char* line = evbuffer_readln(input, &len, EVBUFFER_EOL_CRLF_STRICT);

	/*如果一行还没到，等待一行的到齐*/
	if (NULL == line){
		return;
	}

    char buf[MAXLINE], method[MAXLINE], uri[MAXLINE], version[MAXLINE];
	task temp_task;
	temp_task.fd = bufferevent_getfd(bev);
	temp_task.content_length = 0;
	temp_task.output = bufferevent_get_output(bev);
  
    sscanf(line, "%s %s %s", method, uri, version);
    if (!strcasecmp(method, "GET")){
		temp_task.req_method = GET;
	}else if(!strcasecmp(method, "POST")){
		temp_task.req_method = POST;
	}else{ 
        clienterror(temp_task.output, temp_task.fd, method, "501", "Not Implemented",
                "Xiao's server does not implement this method");
        return;
	}

    read_requesthdrs(input, temp_task.content_length);
	
	if (temp_task.req_method == POST){
		temp_task.input = input;
	}else{
		temp_task.input = NULL;
	}

    /* Parse URI from request */
    temp_task.is_static 
		= parse_uri(temp_task.req_method, uri, temp_task.filename, temp_task.cgiargs);
	
	/*将任务插入任务队列，生产者消费者模型*/
	task_insert(&handler, temp_task);

	free(line);
}

